#!/bin/bash

# 测试集群功能的脚本

set -e

echo "Testing cluster functionality..."

# 基础 URL
BASE_URL="http://127.0.0.1:8081"

# 等待集群启动
echo "Waiting for cluster to be ready..."
for i in {1..30}; do
    if curl -s "$BASE_URL/api/v1/health" >/dev/null 2>&1; then
        echo "Cluster is ready!"
        break
    fi
    echo "Waiting... ($i/30)"
    sleep 2
done

if ! curl -s "$BASE_URL/api/v1/health" >/dev/null 2>&1; then
    echo "Error: Cluster not ready after 60 seconds"
    exit 1
fi

echo ""
echo "=== Testing Cluster API ==="

# 1. 获取集群状态
echo "1. Getting cluster status..."
curl -s "$BASE_URL/api/v1/cluster/status" | jq '.'

echo ""

# 2. 获取集群成员
echo "2. Getting cluster members..."
curl -s "$BASE_URL/api/v1/cluster/members" | jq '.'

echo ""

# 3. 添加测试节点
echo "3. Adding a test node..."
curl -s -X POST "$BASE_URL/api/v1/nodes" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "test-node-1",
    "address": "127.0.0.1:9001",
    "metadata": {
      "environment": "test",
      "region": "local"
    }
  }' | jq '.'

echo ""

# 4. 获取所有节点
echo "4. Getting all nodes..."
curl -s "$BASE_URL/api/v1/nodes" | jq '.'

echo ""

# 5. 获取特定节点信息
echo "5. Getting test node info..."
curl -s "$BASE_URL/api/v1/nodes/test-node-1" | jq '.'

echo ""

# 6. 更新节点元数据
echo "6. Updating node metadata..."
curl -s -X PUT "$BASE_URL/api/v1/nodes/test-node-1" \
  -H "Content-Type: application/json" \
  -d '{
    "address": "127.0.0.1:9001",
    "metadata": {
      "environment": "test",
      "region": "local",
      "updated": true
    }
  }' | jq '.'

echo ""

# 7. 获取节点健康状态
echo "7. Getting node health..."
curl -s "$BASE_URL/api/v1/nodes/test-node-1/health" | jq '.'

echo ""

# 8. 获取集群指标
echo "8. Getting cluster metrics..."
curl -s "$BASE_URL/api/v1/cluster/metrics" | jq '.'

echo ""

# 9. 获取配置信息
echo "9. Getting cluster config..."
curl -s "$BASE_URL/api/v1/cluster/config" | jq '.'

echo ""

# 10. 移除测试节点
echo "10. Removing test node..."
curl -s -X DELETE "$BASE_URL/api/v1/nodes/test-node-1" | jq '.'

echo ""

echo "=== Testing Prometheus Metrics ==="
echo "Getting Prometheus metrics..."
curl -s "http://127.0.0.1:9090/metrics" | head -20

echo ""
echo "=== All tests completed successfully! ==="
